package com.nbst.service.base.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.StringUtils;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.nbst.comnutil.DESUtil;
import com.nbst.comnutil.LogOut;
import com.nbst.comnutil.NormalResult;
import com.nbst.comnutil.StringUtil;
import com.nbst.comnutil.Tools;
import com.nbst.dao.mapper.mes.MachineEmpMapper;
import com.nbst.dao.mapper.mes.UserMapper;
import com.nbst.dao.mapper.mes.UserRoleMapper;
import com.nbst.model.base.Base;
import com.nbst.model.base.User;
import com.nbst.model.base.UserRole;
import com.nbst.service.base.IUserService;

/**
 * @ClassName: UserServiceImpl
 * @Description:用户管理Service实现
 * @author 兵
 * @date 2017-8-16
 * 
 */

@Service
public class UserServiceImpl implements IUserService {

	@Autowired
	UserMapper usermapper;

	@Autowired
	LogOut logout;

	@Autowired
	UserRoleMapper userRoleMapper;

	@Autowired
	MachineEmpMapper machineEmpMapper;

	@Override
	public NormalResult deleteByPrimaryKey(Integer uId) {
		NormalResult result = new NormalResult();
		int num = 0;
		try {
			User user = new User();
			user.setId(uId);
			user.setfClosed(0);
			num = usermapper.updateByPrimaryKeySelective(user);
			if (num == 1) {
				result.setCode("0000");
				result.setMessage("删除成功");
			}
		} catch (Exception e) {
			logout.error(e);
			result.setCode("9999");
			result.setMessage("删除失败");
			result.setDataset(e);
		}
		return result;
	}

	@Override
	@Transactional
	public NormalResult insertSelective(User record, String[] ids) {
		NormalResult result = new NormalResult();
		if (StringUtil.isEmpty(record.getfDepId())) {
			result.setCode("9999");
			result.setDataset("该用户没有选择部门");
			return result;
		}
		record.setfDate(new Date());
		if (StringUtils.isEmpty(record.getPassword())) {
			record.setPassword(DESUtil.encrypt("123456")); // 如果密码为空，则默认为123456并加密
		} else {
			record.setPassword(DESUtil.encrypt(record.getPassword()));// 加密
		}
		int num = 0;
		int n = 0;
		try {
			Map<String, Object> map1 = new HashMap<>();
			map1.put("account", record.getAccount());
			if (usermapper.findByCondition(map1).size() > 0) {
				result.setCode("9999");
				result.setMessage("该用户名已存在");
				return result;
			}
			num = usermapper.insertSelective(record);
			// usermapper.insertSelectiveAPS(record);
			if (ids != null) {
				if (ids.length > 0) {
					Map<String, Object> map = new HashMap<>();
					map.put("id", record.getId());
					List<User> list = usermapper.findByCondition(map);
					if (!list.isEmpty()) {
						UserRole ur = new UserRole();
						ur.setuId(list.get(0).getId());
						ur.setfDate(new Date());

						for (String id : ids) {
							ur.setrId(Integer.parseInt(id));
							userRoleMapper.insertSelective(ur);
							n++;
						}
					}
				}
			}

			result.setCode("0000");
			result.setMessage("新增成功");
			result.setId(record.getId().toString());
		} catch (Exception e) {
			logout.error(e);
			result.setCode("9999");
			result.setMessage("新增失败");
			result.setDataset(e);
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();// 手动回滚
		}

		return result;
	}

	@Override
	public List<User> findByCondition(Map<String, Object> map) {
		List<User> list = new ArrayList<User>();
		try {
			if (map.get("id") != null) {
				if (!StringUtils.isEmpty((map.get("id").toString()))) { // 如果只是用ID查询单个信息
					Map<String, Object> urMap = new HashMap<>();
					urMap.put("uId", map.get("id").toString());
					List<Map<String, Object>> urList = userRoleMapper.getRolesId(urMap);

					List<Map<String, Object>> dList = usermapper
							.getUser2Dep(Integer.parseInt(map.get("id").toString()));
					String rIds = "";
					String dIds = "";
					int flag = 0;
					int n = 0;
					if (urList.size() > 0) {
						for (Map<String, Object> mp : urList) {
							if (flag > 0) {
								rIds = rIds + "," + (mp.get("rId").toString());

								flag++;
							} else {
								rIds = (mp.get("rId").toString());
								flag++;
							}
						}
					}
					if (dList.size() > 0) {
						for (Map<String, Object> mp : dList) {
							if (n > 0) {
								dIds = dIds + "," + (mp.get("dId").toString());
								n++;
							} else {
								dIds = (mp.get("dId").toString());
								n++;
							}
						}
					}
					list = usermapper.findByCondition(map);
					if (!list.isEmpty()) {
						list.get(0).setrIds(rIds);
						list.get(0).setDids(dIds);
					}
				}
			} else {
				list = usermapper.findByCondition(map);
			}
		} catch (Exception e) {
			logout.error(e);
		}
		return list;
	}

	@Override
	@Transactional
	public NormalResult updateByPrimaryKeySelective(User record, String[] rIds) {
		NormalResult result = new NormalResult();
		record.setfDate(new Date());
		if (!StringUtils.isEmpty(record.getPassword())) {
			record.setPassword(DESUtil.encrypt(record.getPassword()));
		}
		int num = 0;
		try {
			if ((rIds.length > 0)) {
				if (!"flag".equals(rIds[0])) {
					userRoleMapper.delete(record.getId());
					UserRole ur = new UserRole();
					ur.setfDate(new Date());
					ur.setuId(record.getId());
					for (String rId : rIds) {
						ur.setrId(Integer.parseInt(rId));
						userRoleMapper.insertSelective(ur);
					}
				}
			} else {
				userRoleMapper.delete(record.getId());
			}

			Map<String, Object> map = new HashMap<>();
			map.put("id", record.getId());
			List<User> users = usermapper.findByCondition(map);
			if (users.size() == 1) {
				if (!users.get(0).getUserCode().equals(record.getUserCode())) {
					if (!StringUtil.isEmpty(record.getUserCode())) {
						map.clear();
						map.put("newWorker", record.getUserCode());
						map.put("oldWorker", users.get(0).getUserCode());
						machineEmpMapper.replaceEmpCardno(map);
					}
				}
			}

			num = usermapper.updateByPrimaryKeySelective(record);
			result.setCode("0000");
			result.setMessage("修改成功");
		} catch (Exception e) {
			logout.error(e);
			result.setCode("9999");
			result.setMessage("出错了,刷新后再试试吧");
			result.setDataset(e);
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();// 手动回滚
		}
		return result;
	}

	@Override
	public int count(Map<String, Object> map) {
		int total = 0;
		try {
			total = usermapper.count(map);
		} catch (Exception e) {
			logout.error(e);
		}
		return total;
	}

	@Override
	public List<Base> getDepartmentUserTree(Map<String, Object> map) {
		List<Base> list = new ArrayList<Base>();
		try {
			list = usermapper.getDepartmentUserTree(map);
		} catch (Exception e) {
			logout.error(e);
		}
		return list;
	}

	@Override
	public List<Map<String, Object>> getUser2Dep(Integer uId) {
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		try {
			list = usermapper.getUser2Dep(uId);
		} catch (Exception e) {
			logout.error(e);
		}
		return list;
	}

	@Override
	@Transactional
	public NormalResult insertUser2Dep(Integer uId, String dIds) {
		NormalResult result = new NormalResult("9999", "添加失败");
		try {
			// 先删除和uId相关的关系数据（用户和部门的关系表）
			usermapper.deleteByuIdUser2Dep(uId);
			if (!StringUtils.isEmpty(dIds)) {
				String[] ids = dIds.split(",");

				if (ids.length > 0) {
					Map<String, Object> map = new HashMap<>(6);
					map.put("uId", uId);
					for (int i = 0; i < ids.length; i++) {
						if (!StringUtils.isEmpty(ids[i])) {
							map.put("dId", ids[i]);
							usermapper.insertUser2Dep(map);
						}
					}
				}
			}
			result.setCode("0000");
			result.setMessage("添加成功");
		} catch (Exception e) {
			logout.error(e);
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();// 手动回滚
		}
		return result;
	}

	@Override
	public Integer[] List2Array(Integer uId) {
		try {
			List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
			Integer[] ids;
			list = usermapper.getUser2Dep(uId);
			if (list.size() > 0) {
				ids = new Integer[list.size()];
				int n = 0;
				for (Map<String, Object> mp : list) {
					ids[n] = Integer.parseInt(mp.get("dId").toString());
					n++;
				}
				return ids;
			}
		} catch (Exception e) {
			logout.error(e);
		}
		return null;
	}

	@Override
	public NormalResult updatePassword(User record) {
		if (!StringUtils.isEmpty(record.getPassword()) && !StringUtils.isEmpty(record.getId())) {
			record.setPassword(DESUtil.encrypt(record.getPassword()));// 加密
			usermapper.updateByPrimaryKeySelective(record);
			return new NormalResult("0000", "修改成功");
		}
		return new NormalResult("9999", "修改失败");
	}

	@Override
	public NormalResult stopUser(User record) {
		NormalResult result = new NormalResult();
		if (StringUtil.isEmpty(record.getId())) {
			result.setMessage("请选择需要操作的账号id");
			return result;
		}
		if (StringUtil.isEmpty(record.getfStop())) {
			result.setMessage("请选择启/停");
			return result;
		}
		try {
			usermapper.updateByPrimaryKeySelective(record);
		} catch (Exception e) {
			logout.error(e);
		}
		return result;
	}

	@Override
	public NormalResult findByCondition1(Map<String, Object> map, Integer offset, Integer row) {
		NormalResult result = new NormalResult();
		List<User> list = new ArrayList<User>();
		Page page;
		try {
			String orderBy = null;
			if (map != null) {
				if (map.get("orderBy") != null) {
					orderBy = map.get("orderBy").toString();
				}
			}
			if (StringUtil.isEmpty(orderBy)) {
				page = PageHelper.startPage(Tools.getPageNum(offset, row), row);
			} else {
				page = PageHelper.startPage(Tools.getPageNum(offset, row), row, orderBy);
			}
			list = usermapper.findByCondition(map);
			if (list.size() == 0) {
				result.setMessage("没有找到数据");
			} else {
				result.setCode("0000");
				result.setMessage("操作成功");
				result.setRows(list);
				result.setTotal(page.getTotal());
			}
		} catch (Exception e) {
			logout.error(e);
		}
		return result;
	}

}